/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.service;

import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.restfb.DefaultFacebookClient;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;
import com.restfb.types.User;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.stereotype.Component;
import ro.futurefeed.model.FacebookQLUser;

/**
 *
 * @author Georgian
 */
@Component
public class FacebookServiceImpl implements FacebookService{
    
    private static final Logger LOG = Logger.getLogger("FutureFeedService");

    @Override
    public User getFbUser(String accessToken) {
        return new DefaultFacebookClient(accessToken).fetchObject("me", User.class);
    }

    @Override
    public String getAccessTokenExtended(String accessToken) {
        return new DefaultFacebookClient(accessToken)
                .obtainExtendedAccessToken(APP_ID, APP_SECRET, accessToken).getAccessToken();
    }

    @Override
    public String postWallFeed(String accessToken, String to, String content) {
        DefaultFacebookClient facebookClient = new DefaultFacebookClient(accessToken);
        FacebookType publishMessageResponse =
                facebookClient.publish((to != null ? to : "me") + "/feed", FacebookType.class,
                Parameter.with("message", content));

        return publishMessageResponse.getId();
    }

    @Override
    public boolean deleteWallPost(String accessToken, String postId) {
        return new DefaultFacebookClient(accessToken).deleteObject(postId);
    }

    @Override
    public String getFacebookAccessToken(String code) throws Exception{
        String oAuthURL = "https://graph.facebook.com/oauth/access_token?"
            + "client_id=" + FacebookService.APP_ID
            + "&client_secret=" + FacebookService.APP_SECRET
            + "&redirect_uri=" + FacebookService.MAIN_PAGE
            + "&code="+code;
        LOG.info("Request FB access token for " + oAuthURL);
        HTTPRequest request = new HTTPRequest(new URL(oAuthURL));
        URLFetchService service = URLFetchServiceFactory.getURLFetchService();
        HTTPResponse response = service.fetch(request);
        String content = new String(response.getContent());
        if(content.contains("error")){
            throw new Exception("Error getting access token: " + content);
        }else{
            String token = content.substring(content.indexOf("=") + 1, content.indexOf("&"));
            return token;
        }
    }

    @Override
    public List<FacebookQLUser> getFriends(String accessToken, String nameFilter) {
        String query = "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) "
                + (nameFilter!=null?"and strpos(lower(name), '"+nameFilter.toLowerCase()+"')>=0 ":"")
                + "order by name asc";
        return new DefaultFacebookClient(accessToken).executeQuery(query, FacebookQLUser.class);
    }
    
}
